<template>
  <div class="reception-container">
    <!-- 左侧列表 -->
    <el-card class="sidebar">
      <div class="sidebar-header">
        <h3>待接诊列表</h3>
        <div class="date-selector">
          <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" @change="handleDateChange" style="width: 100%;" />
        </div>
      </div>
      <el-scrollbar height="calc(100vh - 220px)">
        <el-menu :default-active="selectedPetId" class="pet-menu" @select="handleSelect">
          <el-menu-item v-for="pet in petList" :key="pet.reservationId" :index="pet.reservationId.toString()" :class="{
            'pet-item': true,
            'pet-item--cat': pet.petType.includes('猫'),
            'pet-item--dog': pet.petType.includes('狗')
          }">
            {{ pet.nickname }}（{{ pet.petName }}）
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </el-card>

    <!-- 右侧详情 -->
    <el-card class="main-panel" v-if="selectedPet">
      <h2 class="pet-title">🐾 接诊信息：{{ selectedPet.petName }}</h2>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="品种">
          <span class="pet-type-tag" :class="getPetTypeClass(selectedPet.petType)">{{ selectedPet.petType }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="主人">{{ selectedPet.nickname }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ selectedPet.reservationDate }} {{ selectedPet.reservationTime
        }}</el-descriptions-item>
        <el-descriptions-item label="是否住院">
          <el-switch v-model="form.hospitalization" active-color="#13ce66" inactive-color="#ff4949" />
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <el-form :model="form" label-width="100px" class="medical-form" ref="medicalFormRef">
        <!-- 医疗项目 -->
        <el-form-item label="医疗项目" prop="services">
          <el-select v-model="form.services" multiple placeholder="请选择医疗项目" clearable style="width: 100%">
            <el-option v-for="item in serviceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 药品选择 -->
        <el-form-item label="药品" prop="medications">
          <el-select v-model="tempMedication" filterable remote :remote-method="searchMedications"
            :loading="medicationLoading" placeholder="请输入药品编号、名称或症状进行搜索" clearable style="width: 100%"
            @change="handleMedicationSelect">
            <el-option v-for="medication in medicationOptions" :key="medication.medicineId"
              :label="`${medication.barCode} - ${medication.name} - ${medication.description}`" :value="medication" />
          </el-select>
          <!-- 已选药品显示在下方 -->
          <div class="selected-medicines" v-if="form.medications.length">
            <el-tag v-for="(med, index) in form.medications" :key="index" closable @close="removeMedication(index)"
              :class="getMedicationColorClass(index)">
              {{ med.name }} ({{ med.barCode }})
            </el-tag>
          </div>
        </el-form-item>

        <!-- 诊断结果 -->
        <el-form-item label="诊断结果" prop="diagnosis">
          <el-input v-model="form.diagnosis" type="textarea" :rows="3" placeholder="请输入诊断结果" />
        </el-form-item>

        <!-- 治疗方案 -->
        <el-form-item label="治疗方案" prop="treatment">
          <el-input v-model="form.treatment" type="textarea" :rows="3" placeholder="请输入治疗方案" />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="form.notes" :rows="2" />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 无选中宠物提示 -->
    <el-card class="main-panel" v-else>
      <el-empty description="请选择待接诊的宠物" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { queryDoctorPatient } from '@/api/appointment'
import { getQueryPage } from '@/api/medicine'
import { addMedication } from '@/router/modules/MedicalRecord'

const petList = ref([])
const selectedPetId = ref('')
const selectedDate = ref(null)
const medicalFormRef = ref(null)
const submitLoading = ref(false)

// 药品相关
const medicationOptions = ref([])
const medicationLoading = ref(false)
const tempMedication = ref(null)

// 医疗项目
const serviceOptions = [
  { label: '体检', value: '体检' },
  { label: '疫苗接种', value: '疫苗接种' },
  { label: '手术', value: '手术' },
  { label: '驱虫', value: '驱虫' },
  { label: '绝育', value: '绝育' },
  { label: '牙科护理', value: '牙科护理' }
]

// 表单数据
const form = ref({
  hospitalization: false,
  services: [],
  medications: [], // 存储完整的药品对象
  diagnosis: '',
  treatment: '',
  notes: ''
})

// 获取待接诊列表
const fetchPetList = async (date) => {
  try {
    const res = await queryDoctorPatient(date)
    petList.value = res?.data.data || []
    // 默认选中第一条
    if (petList.value.length > 0) {
      selectedPetId.value = petList.value[0].reservationId.toString()
      resetForm()
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('获取待接诊列表失败')
  }
}

onMounted(() => {
  const today = new Date()
  const yyyy = today.getFullYear()
  const mm = String(today.getMonth() + 1).padStart(2, '0')
  const dd = String(today.getDate()).padStart(2, '0')
  selectedDate.value = `${yyyy}-${mm}-${dd}`
  fetchPetList(selectedDate.value)
})

// 处理日期变化
const handleDateChange = (date) => fetchPetList(date)

// 选中宠物
const handleSelect = (id) => {
  selectedPetId.value = id
  resetForm()
}

// 选中的宠物对象
const selectedPet = computed(() => {
  if (!selectedPetId.value) return null
  return petList.value.find(p => p.reservationId.toString() === selectedPetId.value)
})

// 药品搜索
const searchMedications = (query) => {
  if (!query) {
    medicationOptions.value = []
    return
  }

  medicationLoading.value = true
  let params = {
    current: 1,
    size: 10,
    searchQuery1: query
  }

  getQueryPage(params).then(res => {
    medicationOptions.value = res?.data.records || []
    medicationLoading.value = false
  }).catch(() => {
    medicationLoading.value = false
    ElMessage.error('药品搜索失败')
  })
}

// 处理药品选择
const handleMedicationSelect = (medication) => {
  if (medication && !form.value.medications.some(m => m.medicineId === medication.medicineId)) {
    form.value.medications.push(medication)
  }
  tempMedication.value = null
}

// 移除药品
const removeMedication = (index) => {
  form.value.medications.splice(index, 1)
}

// 表单验证规则

// 提交表单
const submitForm = async () => {
  if (!selectedPet.value) {
    ElMessage.warning('请先选择宠物')
    return
  }

  try {
    // 表单验证
    await medicalFormRef.value.validate()

    submitLoading.value = true
    debugger
    // 构建提交数据
    const submitData = {
      doctorId: selectedPet.value.doctorId,
      reservationId: selectedPet.value.reservationId, // 从当前选中数据获取 reservationId
      phone: selectedPet.value.phone,
      nickname: selectedPet.value.nickname,
      petId: selectedPet.value.petId || null, // 如果有petId的话

      diagnosis: form.value.diagnosis,
      treatment: form.value.treatment,
      hospitalization: form.value.hospitalization ? '2' : '1',
      medicalServices: JSON.stringify(form.value.services),
      medications: JSON.stringify(form.value.medications.map(med => ({
        medicineId: med.medicineId,
        name: med.name,
        barCode: med.barCode,
        description: med.description
      }))),
      notes: form.value.notes
    }

    console.log('提交数据:', submitData)

    // 这里调用提交API
    await addMedication(submitData).then(resp => {
      if (resp.code === 200) {
        ElMessage.success('接诊信息提交成功！')
        resetForm()
        onMounted() // 重新加载列表
      } else {
        ElMessage.error('接诊信息提交失败！')
      }
    })

  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error('表单验证失败，请检查输入')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    hospitalization: false,
    services: [],
    medications: [],
    diagnosis: '',
    treatment: '',
    notes: ''
  }
  tempMedication.value = null
}

// 宠物类型样式
const getPetTypeClass = (petType) => {
  if (petType.includes('猫')) return 'pet-type-cat'
  if (petType.includes('狗')) return 'pet-type-dog'
  return 'pet-type-other'
}

// 药品标签颜色
const getMedicationColorClass = (index) => {
  const colors = ['medication-tag-blue', 'medication-tag-green', 'medication-tag-yellow', 'medication-tag-red', 'medication-tag-purple']
  return colors[index % colors.length]
}
</script>

<style scoped>
.reception-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100vh;
}

.sidebar {
  width: 300px;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.sidebar-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.sidebar-header h3 {
  margin: 0 0 15px 0;
}

.pet-menu {
  border-right: none;
}

.pet-item {
  border-radius: 8px;
  margin: 5px;
  transition: all 0.3s;
}

.pet-item:hover {
  transform: translateX(5px);
}

.pet-item--cat {
  border-left: 4px solid #FF9999;
}

.pet-item--dog {
  border-left: 4px solid #64B5F6;
}

.main-panel {
  flex: 1;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.pet-title {
  color: #409EFF;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.pet-type-tag {
  padding: 5px 10px;
  border-radius: 15px;
  color: white;
  font-weight: bold;
}

.pet-type-cat {
  background: linear-gradient(120deg, #FF9999 0%, #FF6666 100%);
}

.pet-type-dog {
  background: linear-gradient(120deg, #64B5F6 0%, #1E88E5 100%);
}

.pet-type-other {
  background: linear-gradient(120deg, #81C784 0%, #4CAF50 100%);
}

.medical-form {
  display: flex;
  flex-direction: column;
}

.selected-medicines {
  margin-top: 8px;
  color: red;
}

.medicine-tag {
  margin-right: 6px;
  margin-top: 6px;
}

.medication-tag-blue {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}

.medication-tag-green {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
}

.medication-tag-yellow {
  background-color: #E6A23C !important;
  border-color: #E6A23C !important;
}

.medication-tag-red {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
}

.medication-tag-purple {
  background-color: #926de6 !important;
  border-color: #926de6 !important;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.form-actions .el-button+.el-button {
  margin-left: 10px;
}

.date-selector {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.date-selector:hover {
  border-color: #409eff;
}
</style>